#include "../include/MainHeader.h"

#define MAXBUCKETS 27
#define SUCCESS 1
#define RECORD_NOT_DELETED 4
#define UNABLE_TO_OPEN_FILE 10
#define EMPTY_FILE 5

void createHashTable(struct HashTable *hash) {

	int i,j;
	struct LinkedListNode* node;
	char *ch[]={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","notalpha"};
	
	for(i = 0; i < MAXBUCKETS; i++) {
		hash->buckets[i] = (struct LinkedListNode*) malloc(sizeof(struct LinkedListNode));
		hash->buckets[i]->fileDesc = (fd *) malloc (sizeof(fd));

		strcpy(hash->buckets[i]->fileDesc->file_name,ch[i]);
		hash->buckets[i]->next = NULL;
	}
}

int calcHash(char *file_name) {
	
	int keyVal = toascii(toupper(*file_name))-65;
	//printf("keyval=%d",keyVal);
	return keyVal;
}

void hashInsert(struct HashTable *hash, fd data) {

	int keyVal;

	keyVal = calcHash(data.file_name);

	if(keyVal<0 || keyVal>25) {
		keyVal = 26;
	}
	insertIntoLinkedList(&(hash->buckets[keyVal]), data);
}



void hashDelete(struct HashTable *hash,fd data) {

	int keyVal;

	keyVal = calcHash(data.file_name);
	
	deleteFromLinkedList(&(hash->buckets[keyVal]), data);
}
/*
void hashDirDelete(struct HashTable *hash,fd data[]) {

	int keyVal, deleteFlag = 0;
	
	for(int i = 0; i<data.length; i++) {
		keyVal = calcHash(data[i].file_name);
		printf("%d to be deleted\n",keyVal);
		deleteFromLinkedList(&(hash->buckets[keyVal]), data[i]);
	}
}
*/
/*
struct LinkedListNode* hashSearch(struct HashTable *hash, fd data) {
	int keyVal, searchFlag = 0;
	struct LinkedListNode* searchedList;

	keyVal = calcHash(data.file_name);
	searchedList = searchLinkedList(&(hash->buckets[keyVal]), data);

	if(searchedList == NULL) {
		printf("Seach key %s not present\n", data.file_name);
	} else {
		
		printf("Seach key is present\n");
	}

	//if(searchFlag == 0) {
	//	printf("Seach key %s not present\n", data.file_name);
	//}
	//else {
	///	printf("Seach key %s found successfully %d times\n", data.file_name, searchFlag);
	//}

	return searchedList;

	
}
*/

void hashPrefixSearch(struct HashTable *hash, char *data, char* outputFile) {
	
	//printf("\nIn hashsearch\n");
	int keyVal;

	keyVal = calcHash(data);
	//printf("keyval=%d",keyVal);
	searchPrefixLinkedList(&(hash->buckets[keyVal]), data, outputFile);

}

void loadHashTable(fd data[], struct HashTable *hash,int size) {

    	int i;
		
	createHashTable(hash);

	for(i = 0; i<size; i++) {
		hashInsert(hash, data[i]);
	}

	//printf("All the value from the file loaded into hash table successfully\n");
}

void updateHashFileDesc(struct HashTable *hash,fd *data, char* newPath)
{

	//printf("file name in hash=%s\n",data->file_name);
	int keyVal;

	keyVal = calcHash(data->file_name);
	
		
	updateFileDesc(&(hash->buckets[keyVal]), *data, newPath);
}





